﻿@inject IHttpService _httpService
@inject ILocalStorageService _localStorage
@inject IJSRuntime JS

@code {
    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    private DeviceIdentificationModel Model { get; set; } = new DeviceIdentificationModel();

    [CascadingParameter]
    private ConnectionInfo? connectionInfo { get; set; }

    public async Task<DeviceIdentificationModel> GetDeviceIdentificationModel()
    {
        await Load();
        await Refresh();
        await Save();
        return Model;
    }

    public async Task Refresh()
    {
        if (string.IsNullOrWhiteSpace(Model.Cookie))
        {
            Model.Cookie = Guid.NewGuid().ToString();
        }

        if (string.IsNullOrWhiteSpace(connectionInfo?.RemoteIpAddress)==false)
        {
            Model.Ip = connectionInfo?.RemoteIpAddress;
        }
        else
        {
            try
            {
                var client = await _httpService.GetClientAsync();
                Model.Ip = await client.GetStringAsync("https://api.cngal.org/api/account/GetIp");
            }
            catch (Exception ex)
            {
                await ErrorHandler.ProcessError(ex, "网络异常");
            }
        }
        Model.UA = await JS.InvokeAsync<string>("getUserAgent");
    }

    public async Task Load()
    {
        try
        {
            Model = await _localStorage.GetItemAsync<DeviceIdentificationModel>("DeviceIdentification");
            if (Model == null)
            {
                Model = new DeviceIdentificationModel();
            }
        }
        catch
        {

        }

    }
    public async Task Save()
    {
        try
        {
            await _localStorage.SetItemAsync("DeviceIdentification", Model);
        }
        catch
        {

        }

    }
}
